<template>
  <tl-sub-page :render="render" :visible.sync="visible" v-dialogDrag :title="title" :close-on-click-modal="false" class="tl-dialog" width="1200px" @open="open" @close="close">
    <el-row type="flex" :gutter="2" justify="center" style="margin:6px">
      <el-tag type="danger">当前毛利率为{{(computeGrossProfitRate*100).toFixed(2)}}%。</el-tag>&nbsp;&nbsp;
      <el-tag type="danger" v-if="model.orgcodevisible=='D26'">请上传客户签字盖章的设计意向书，再提交审批。</el-tag>
    </el-row>
    <el-tabs type="border-card" :value="tabName">
      <el-tab-pane label="项目信息" name="projectInfo">
        <el-form class="tl-form" ref="form" :model="model" :rules="rules" label-width="120px" :disabled="disableEditSubmit || disableSave">
          <el-row>
            <el-col :span="24">
              <el-divider content-position="left"><span>【项目】基本信息&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; <span style="color:red"></span></span></el-divider>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="12">
              <el-form-item label="客户名称" prop="customercode" :rules="rulesProject">
                <el-input v-model="model.dispcustomercode" :disabled="true" class="tl-ref-selector">
                  <el-button slot="append" type="primary" icon="el-icon-search" @click="openpmCustomerRefDialog" v-if="!disableEditSubmit && !disableSave"></el-button>
                </el-input>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="项目名称" prop="name" :rules="rulesProject">
                <el-input v-model="model.name"></el-input>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="12">
              <el-form-item label="所属省份" prop="province" :rules="rulesProject">
                <!-- <el-input v-model="model.province"></el-input> -->
                <el-select v-model="model.province" filterable clearable>
                  <el-option v-for="item in codeModel.provinceList" :key="item.code" :label="item.name" :value="item.code" />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="项目编号" prop="code">
                <el-input v-model="model.code" :disabled="true"></el-input>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="12">
              <el-form-item label="项目金额" prop="projectmoney" :rules="rulesProject">
                <el-input-number v-model="model.projectmoney" controls-position="right" :step="1" :min="0" style="width:95%"></el-input-number>
                <span>元</span>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="预算总金额" prop="budgetmoney">
                <el-input-number v-model="model.budgetmoney" controls-position="right" :step="1" style="width:95%" :disabled="true"></el-input-number>
                <span>元</span>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <!-- <el-col :span="12">
              <el-form-item label="项目级别" prop="projectlevel" :rules="rulesProject">
                <el-select v-model="model.projectlevel" filterable clearable>
                  <el-option v-for="item in codeModel.projectlevelList" :key="item.code" :label="item.name" :value="item.code" />
                </el-select>
              </el-form-item>
            </el-col> -->
            <el-col :span="12">
              <el-form-item label="项目成果" prop="projectresult">
                <el-input v-model="model.projectresult"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="项目类别" prop="category" :rules="rulesProject">
                <el-select v-model="model.category" filterable clearable>
                  <el-option v-for="item in codeModel.categoryList" :key="item.code" :label="item.name" :value="item.code" />
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="12">
              <el-form-item label="所属部门" prop="ownerdeptname" :rules="rulesProject">
                <tl-ref-dept v-model="model.ownerdeptname" :initDisplayData.sync="model.ownerdeptname" dataType="code" @confirm="onSelectDept" :disabled="disableEditSubmit || disableSave" nameType="fullname" :singleSelect="true" :externalQueryParam="{qry_enabled:1}"></tl-ref-dept>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="所属公司" prop="ownerorgname">
                <el-input v-model="model.ownerorgname" :readonly="true" class="is-disabled"></el-input>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="12">
              <el-form-item label="项目经理" prop="projectmanagername" :rules="rulesProject">
                <tl-ref-user v-model="model.projectmanagername" :initDisplayData.sync="model.projectmanagername" :disabled="disableEditSubmit || disableSave" dataType="code" :singleSelect="true" @confirm="projectmanagernameConfirm"></tl-ref-user>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="销售经理" prop="areamanagername" :rules="rulesProject">
                <tl-ref-user v-model="model.areamanagername" :initDisplayData.sync="model.areamanagername" :disabled="disableEditSubmit || disableSave" @confirm="areamanagernameConfirm" dataType="code" :singleSelect="true"></tl-ref-user>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="12">
              <el-form-item label="立项批准人" prop="approvalname" v-show="model.projectstate != '0' && model.projectstate != null">
                <tl-ref-user v-model="model.approvalname" :initDisplayData.sync="model.approvalname" :disabled="true" dataType="code" :singleSelect="true"></tl-ref-user>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="立项日期" prop="approvaltime" v-show="model.projectstate != '0' && model.projectstate != null">
                <el-date-picker v-model="model.approvaltime" type="date" placeholder="立项日期" :disabled="true" value-format="yyyy-MM-dd"></el-date-picker>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="12">
              <el-form-item label="计划开工日期" prop="planstarttime" :rules="rulesProject">
                <el-date-picker v-model="model.planstarttime" type="date" placeholder="例如：2021-01-01" value-format="yyyy-MM-dd" @change="planStart"></el-date-picker>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="计划完工日期" prop="planendtime" :rules="rulesProject">
                <el-date-picker v-model="model.planendtime" type="date" placeholder="例如：2021-01-01" value-format="yyyy-MM-dd" @change="planEnd"></el-date-picker>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="12">
              <el-form-item label="人天估算" prop="mandays" :rules="rulesProject">
                <el-row>
                  <el-col :span="22">
                    <el-input-number v-model="model.mandays" controls-position="right" :step="1" :min="0" style="width:98%"></el-input-number>
                  </el-col>
                  <el-col :span="2">
                    <tl-help>
                      人天指的是一个人工作一天的工作量，简单预估项目的总体工作量
                    </tl-help>
                  </el-col>
                </el-row>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="12">
              <el-form-item label="是否含产品" prop="isincludeproducts">
                <el-select v-model="model.isincludeproducts" filterable clearable>
                  <el-option v-for="item in codeModel.isincludeproductsList" :key="item.code" :label="item.name" :value="item.code" />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="是否外包" prop="ispurchase" :rules="rulesProject">
                <el-select v-model="model.ispurchase" filterable clearable>
                  <el-option v-for="item in codeModel.ispurchaseList" :key="item.code" :label="item.name" :value="item.code" />
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="24">
              <el-form-item label="产品明细" prop="productdetails" v-show="model.isincludeproducts == '1'" :rules="model.isincludeproducts == '1' ? rulesProject : { required: false }">
                <el-input v-model="model.productdetails" type="textarea" :rows="2"></el-input>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="24">
              <el-form-item label="外包说明" prop="purchasedescription" v-show="model.ispurchase == '1'" :rules="model.ispurchase == '1' ? rulesProject : { required: false }">
                <el-input v-model="model.purchasedescription" type="textarea" :rows="2"></el-input>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="24">
              <el-form-item label="项目背景" prop="background">
                <el-input v-model="model.background" type="textarea" :rows="2"></el-input>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="24">
              <el-form-item label="项目概况" prop="overview">
                <el-input v-model="model.overview" type="textarea" :rows="2"></el-input>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="24">
              <el-form-item label="项目目标" prop="projecttarget" :rules="rulesProject">
                <el-input v-model="model.projecttarget" type="textarea" :rows="2"></el-input>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="24">
              <el-form-item label="承接原因" prop="reason">
                <el-input v-model="model.reason" type="textarea" :rows="2"></el-input>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="24">
              <el-form-item label="风险评估" prop="riskassessment" :rules="rulesProject">
                <el-input v-model="model.riskassessment" type="textarea" :rows="2"></el-input>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="24">
              <el-form-item label="应对策略" prop="riskcountermeasures" :rules="rulesProject">
                <el-input v-model="model.riskcountermeasures" type="textarea" :rows="2"></el-input>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="24">
              <el-form-item label="备注" prop="description">
                <el-input v-model="model.description" type="textarea" :rows="2"></el-input>
              </el-form-item>
            </el-col>
          </el-row>
          <el-form class="tl-form" ref="monitorform" :model="model" :rules="rules" label-width="120px" :disabled="disableEditSubmit || disableSave" v-show="model.projectstate != '0' && model.projectstate != null">
            <el-row>
              <el-col :span="24">
                <el-divider content-position="left"><span>【项目财务】相关信息</span></el-divider>
              </el-col>
            </el-row>
            <el-row>
              <el-col :span="12">
                <el-form-item label="合同总金额" prop="contractmoney">
                  <el-input-number v-model="model.contractmoney" controls-position="right" :step="1" style="width:95%" :disabled="true"></el-input-number>
                  <span>元</span>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="收款总金额" prop="recbillmoney">
                  <el-input-number v-model="model.recbillmoney" controls-position="right" :step="1" :min="0" style="width:95%" :disabled="true"></el-input-number>
                  <span>元</span>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row>
              <el-col :span="12">
                <el-form-item label="开票总金额" prop="billmoney">
                  <el-input-number v-model="model.billmoney" controls-position="right" :step="1" style="width:95%" :disabled="true"></el-input-number>
                  <span>元</span>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="收据总金额" prop="receiptmoney">
                  <el-input-number v-model="model.receiptmoney" controls-position="right" :step="1" style="width:95%" :disabled="true"></el-input-number>
                  <span>元</span>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row>
              <el-col :span="12">
                <el-form-item label="确认收入总金额" prop="confirmrevenuemoney">
                  <el-input-number v-model="model.confirmrevenuemoney" controls-position="right" :step="1" :min="0" style="width:95%" :disabled="true"></el-input-number>
                  <span>元</span>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="成本总金额" prop="costmoney">
                  <el-input-number v-model="model.costmoney" controls-position="right" :step="1" :min="0" style="width:95%" :disabled="true"></el-input-number>
                  <span>元</span>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row>
              <el-col :span="12">
                <el-form-item label="采购申请金额" prop="purchasemoney">
                  <el-input-number v-model="model.purchasemoney" controls-position="right" :step="1" :min="0" style="width:95%" :disabled="true"></el-input-number>
                  <span>元</span>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="采购合同金额" prop="purchasecontractmoney">
                  <el-input-number v-model="model.purchasecontractmoney" controls-position="right" :step="1" style="width:95%" :disabled="true"></el-input-number>
                  <span>元</span>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row>
              <el-col :span="12">
                <el-form-item label="采购付款金额" prop="purchasepaymentmoney">
                  <el-input-number v-model="model.purchasepaymentmoney" controls-position="right" :step="1" :min="0" style="width:95%" :disabled="true"></el-input-number>
                  <span>元</span>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row>
              <el-col :span="24">
                <el-divider content-position="left"><span>【项目监控】相关信息</span></el-divider>
              </el-col>
            </el-row>
            <el-row>
              <el-col :span="12">
                <el-form-item label="超期状态" prop="overduestatus">
                  <el-select v-model="model.overduestatus" filterable clearable :disabled="true">
                    <el-option v-for="item in codeModel.overduestatusList" :key="item.code" :label="item.name" :value="item.code" />
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="项目进度状态" prop="projectstate">
                  <el-select v-model="model.dispprojectstate" filterable clearable :disabled="true">
                    <el-option v-for="item in codeModel.projectstateList" :key="item.code" :label="item.name" :value="item.code" :disabled="true" />
                  </el-select>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row>
              <el-col :span="12">
                <el-form-item label="实际开工日期" prop="actualstarttime">
                  <el-date-picker v-model="model.actualstarttime" type="date" placeholder="实际开工日期" value-format="yyyy-MM-dd" :disabled="true"></el-date-picker>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="实际完工日期" prop="actualendtime">
                  <el-date-picker v-model="model.actualendtime" type="date" placeholder="实际完工日期" value-format="yyyy-MM-dd" :disabled="true"></el-date-picker>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row>
              <el-col :span="12">
                <el-form-item label="实际闭环日期" prop="actualclosetime">
                  <el-date-picker v-model="model.actualclosetime" type="date" placeholder="实际闭环日期" value-format="yyyy-MM-dd" :disabled="true"></el-date-picker>
                </el-form-item>
              </el-col>
            </el-row>
          </el-form>
          <el-collapse>
            <el-collapse-item title="【单据】相关信息">
              <el-row>
                <el-col :span="12">
                  <el-form-item label="申请部门" prop="deptname">
                    <tl-ref-dept v-model="model.deptcode" :initDisplayData.sync="model.deptname" :disabled="true" dataType="code" nameType="fullname" :singleSelect="true" :externalQueryParam="{qry_enabled:1}"></tl-ref-dept>
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label="申请公司" prop="orgname">
                    <el-input v-model="model.orgname" :readonly="true" class="is-disabled"></el-input>
                  </el-form-item>
                </el-col>
              </el-row>
              <el-row>
                <el-col :span="12">
                  <el-form-item label="申请人" prop="username">
                    <tl-ref-user v-model="model.username" :initDisplayData.sync="model.username" :disabled="true" dataType="code" :singleSelect="true"></tl-ref-user>
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label="申请人工号" prop="usercode">
                    <el-input v-model="model.usercode" :readonly="true" class="is-disabled"></el-input>
                  </el-form-item>
                </el-col>
              </el-row>
              <el-row>
                <el-col :span="12">
                  <el-form-item label="单据日期" prop="docdate" :rules="rulesProject">
                    <el-date-picker v-model="model.docdate" type="date" placeholder="单据日期" value-format="yyyy-MM-dd"></el-date-picker>
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label="提交时间" prop="submitdate">
                    <el-date-picker v-model="model.submitdate" type="datetime" placeholder="提交时间" disabled></el-date-picker>
                  </el-form-item>
                </el-col>
              </el-row>
              <el-row>
                <el-col :span="12">
                  <el-form-item label="审批流程" prop="flowid">
                    <el-input v-model="model.dispflowid" :readonly="true" class="is-disabled"></el-input>
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label="状态" prop="state">
                    <el-input v-model="model.dispstate" disabled></el-input>
                  </el-form-item>
                </el-col>
              </el-row>
            </el-collapse-item>
          </el-collapse>
        </el-form>
      </el-tab-pane>
      <el-tab-pane label="预算明细" name="bugetInfo">
        <div style="margin-top:10px;" class="aaa">
          <!-- 预算详细 -->
          <el-form :rules="modelForBudget.rules" :model="modelForBudget" ref="budgetForm" :disabled="disableEditSubmit || disableSave">

            <el-table border :data="modelForBudget.tableData" style="width: 100%;" :default-sort="{prop: 'date', order: 'descending'}">
              <el-table-column width="250px" align="center" label="费用类别">
                <template slot-scope="scope">
                  <el-form-item :prop="'tableData.' + scope.$index + '.costtype'" :rules='modelForBudget.rules.costtype'>
                    <el-select style="width:235px" v-model="scope.row.costtype" placeholder="">
                      <el-option v-for="item in costtypeListForBudget" :key="item.code" :label="item.name" :value="item.code" />
                    </el-select>
                  </el-form-item>
                </template>
              </el-table-column>
              <el-table-column width="200px" align="center" label="预算金额">
                <template slot-scope="scope">
                  <el-form-item :prop="'tableData.' + scope.$index + '.budgetmoney'" :rules='modelForBudget.rules.budgetmoney'>
                    <el-input-number style="width:160px" v-model="scope.row.budgetmoney" controls-position="right" :min="0"></el-input-number>
                    <span>元</span>
                  </el-form-item>
                </template>
              </el-table-column>
              <el-table-column width="300px" align="center" label="预算描述">
                <template slot-scope="scope">
                  <el-form-item :prop="'tableData.' + scope.$index + '.note'" :rules='modelForBudget.rules.note'>
                    <el-input style="width:280px;" v-model="scope.row.note"></el-input>
                  </el-form-item>
                </template>
              </el-table-column>
              <el-table-column label="操作">
                <template slot-scope="scope">
                  <el-button @click="addLineForBudget" class="addBtn" v-if="scope.$index == modelForBudget.tableData.length - 1">
                    <i class="el-icon-plus"></i>
                  </el-button>
                  <el-button v-if="modelForBudget.tableData.length > 1" @click="handleDeleteForBudget(scope.$index, scope.row)" class="del-btn">
                    <i class="el-icon-minus"></i>
                  </el-button>
                  <!-- <el-button size="small" @click="handleDelete(scope.$index, scope.row)">删除</el-button> -->
                </template>
              </el-table-column>
            </el-table>
          </el-form>
        </div>
      </el-tab-pane>
    </el-tabs>

    <tl-approval-history ref="history" sourceType="PmProject" :sourceId="model.id" />
    <div slot="footer" class="dialog-footer">
      <el-button :type="disableEditSubmit === false ? 'text' : 'primary'" @click="doCancelEdit" v-if="uiOperateState<=2">取消</el-button>
      <el-button type="primary" @click="doSubmitEdit" :loading="saveLoading" v-if="!disableEditSubmit" :disabled="disableSave">
        <svg-icon icon-class="save" />保存
      </el-button>
      <tl-attachment sourceType="PmProject" :sourceId="model.id" :disabled="disableAttachment" btnTitle="项目文件"></tl-attachment>
      <el-button type="primary" @click="doSubmitApproval" :loading="submitLoading" v-if="!disableEditSubmit" :disabled="disableApproval">
        <svg-icon icon-class="send" />提交审批
      </el-button>
      <el-button type="primary" @click="$refs.history.visible = true" :disabled="disableApprovalHistory">
        <svg-icon icon-class="list" />审批历史
      </el-button>
      <el-button type="primary" @click="doDelApproval" :loading="delApprovalLoading" v-if="!disableDelApproval" :disabled="disableDelApproval">
        <svg-icon icon-class="undo" />取消审批
      </el-button>
    </div>
    <tlpm-customer-ref ref="pmCustomerRef" @confirm="getpmCustomerRefData" :isSingleSelect="true"></tlpm-customer-ref>
    <!-- <tl-help class="help-view"></tl-help> -->
  </tl-sub-page>
</template>

<script>
/** mixins */
import { mixin_approval_edit } from '@tapui/mixins/mixin_approval_edit'
import { mixin_validate } from '@/mixins/mixin_validate'
import tlHelp from '@/components/help/help'
/** 子组件 */
import tlpmCustomerRef from '@/views/ProjectManage/pmCustomer/refList.vue'
/** 工具类 */
import { putAction, getAction, postAction, deleteAction } from '@tapui/utils/http'
/** VUE配置 */
export default {
  mixins: [mixin_approval_edit, mixin_validate],
  components: { tlpmCustomerRef, tlHelp },
  data() {
    var validateForTab = (rule, value, callback) => {
      if (value === '' || value === undefined) {
        this.tabName = rule.tabname
        this.$nextTick(() => {
          var thisFormItem
          if (this.$refs.budgetForm) {
            thisFormItem = this.$refs.budgetForm.fields.filter((element) => {
              if (element.prop === rule.field) {
                return true
              }
            })
          }
          if (!thisFormItem || thisFormItem.length === 0) {
            thisFormItem = this.$refs.form.fields.filter((element) => {
              if (element.prop === rule.field) {
                return true
              }
            })
          }
          if (this.$refs.budgetForm) {
            this.$refs.budgetForm.fields.forEach((element) => {
              if (element.prop === rule.field && this.focuxItem === '' && (element.$children[1].$options._componentTag.indexOf('el-input') !== -1 || element.$children[1].$options._componentTag.indexOf('el-textarea') !== -1) && !element.$children[1].disabled) {
                this.focuxItem = element.prop
                element.$children[1].focus()
              }
            })
          }
          this.$refs.form.fields.forEach((element) => {
            if (element.prop === rule.field && this.focuxItem === '' && (element.$children[1].$options._componentTag.indexOf('el-input') !== -1 || element.$children[1].$options._componentTag.indexOf('el-textarea') !== -1) && !element.$children[1].disabled) {
              this.focuxItem = element.prop
              element.$children[1].focus()
            }
          })
          if (rule.message) {
            callback(new Error(rule.message))
          } else {
            callback(new Error(thisFormItem[0].label + "不得为空"))
          }
        })
      } else {
        callback()
      }
    }
    return {
      moduleTitle: '项目基本信息',
      urlPrefix: '/pm/project/',
      url: {
        // 额外的url
        queryOrgByDeptId: '/pm/customer/queryOrgByDeptId'
      },
      aaa: true,
      rulesProject: [{ validator: validateForTab, tabname: 'projectInfo', trigger: 'change', required: true }],
      costtypeListForBudget: [],
      projectSystemParam: [],
      minProfit: '',
      tipsMinProfit: '',
      messageMinprofit: '',
      messageTipsMinProfit: '',
      disableAttachmentButton: true,
      tabName: 'projectInfo',
      budgetmoneydb: ''
    }
  },
  created() {
    // 获取预算类别
    getAction('pm/budgetLine/dataCodeList').then(res => {
      this.costtypeListForBudget = res.result.costtypeList
    })
  },
  computed: {
    // 计算毛利率
    computeGrossProfitRate() {
      // 计算预算金额
      var budgetmoneyTotal = 0
      this.modelForBudget.tableData.forEach(item => {
        if (item.budgetmoney !== undefined) {
          budgetmoneyTotal = item.budgetmoney + budgetmoneyTotal
        }
      })
      // 毛利计算公式：（项目金额-预算金额）/项目金额
      if (this.model.projectmoney !== 0 && this.model.projectmoney !== undefined) {
        if (this.budgetmoneydb !== '') {
          return ((this.model.projectmoney - this.budgetmoneydb) / this.model.projectmoney).toFixed(4)
        }
        return ((this.model.projectmoney - budgetmoneyTotal) / this.model.projectmoney).toFixed(4)
      } else {
        return 0.0
      }
    }
  },
  methods: {
    // loaded() {
    //   this.disableAttachmentButton = false
    //   if (this.isAdd === false && this.disableEditSubmit === true) {
    //     var params = {
    //       sourceType: 'PmProject',
    //       sourceId: this.model.id
    //     }
    //     getAction('/cbo/attachment/calculateCount', params).then((res) => {
    //       if (res.success) {
    //         if (res.result === 0) {
    //           this.disableAttachmentButton = true
    //         }
    //       }
    //     })
    //   }
    // },
    planStart(e) {

    },
    planEnd(e) {
      if (this.model.planstarttime === '' || typeof this.model.planstarttime === 'undefined') {
        this.$tap.alert('请先选择计划开工日期！', 'warning')
        this.$set(this.model, "planendtime", '')
        return
      }
      var c = new Date(this.model.planstarttime).getTime()
      var d = new Date(this.model.planendtime).getTime()
      if (c > d) {
        this.$tap.alert('计划开工日期不得大于计划完工日期！', 'warning')
        this.$set(this.model, "planendtime", '')
        return
      }
    },
    validatePrice(str) {
      const reg = /(^[1-9]([0-9]{1,4})?(\.[0-9]{1,2})?$)|(^(0){1}$)|(^[0-9]\.[0-9]([0-9])?$)/
      var result = reg.test(str)
      debugger
      return reg.test(str)
    },
    // 切换TAB之前的钩子函数
    leaveTab(activeName, oldActiveName) {
      // 验证预算信息
      if (oldActiveName === 'bugetInfo') {
        var resultForValidate = false
        this.$refs['budgetForm'].validate(valid => {
          if (valid) {
            // 允许切换返回true
            resultForValidate = true
          } else {
            resultForValidate = false
          }
        })
        // 如果当前tab为项目信息 则需要赋值给预算list，用于实时展示毛利率
        if (activeName === 'projectinfo') {
        }
        return resultForValidate
      }
    },
    // provinceChange(selectedOption) {
    //     var province = this.codeModel.provinceList.find(item => {
    //         return item.code === selectedOption
    //     })
    //     this.$set(this.model, 'province', province.name)
    // },
    // 添加预算明细
    addLineForBudget() {
      this.modelForBudget.tableData.push({
        costtype: '',
        budgetmoney: undefined,
        note: ''
      })
    },
    /** 页面打开时执行 - zhanglongfei 2019.10.18 */
    open() {
      this.model = {}
      this.$nextTick(() => {
        this.$refs.form.clearValidate()
        if (this.isAdd === true) {
          this.title = '添加' + this.moduleTitle
          // 需要添加重复判断
          if (this.$store.getters.param.isAvoidRepeat === true) {
            this.queryBillUid()
          }
          if (this.isQueryInitData === true) {
            // 后台进行数据初始化
            this.queryInitData().then(_ => {
              this.assignDefaultValue()
              this.loaded()
            })
          } else {
            // 前台进行数据初始化
            this.$set(this.model, 'enabled', 1)
            this.$set(this.model, 'sortcode', 0)
            this.assignDefaultValue()
            this.loaded()
          }
          // 如果当前用户所在的省区部门为二级部门(例如：鼎信股份\山东营销服务中心\青岛区域)，项目的所属部门默认赋值为二级部门(用户仍可修改)，所属公司为所在公司
          // 如果当前用户所在的省区部门不是区域级别的，不需要赋值
          if (this.$store.getters.dept.fullname.indexOf('区域') !== -1) {
            // 部门信息
            this.$set(this.model, 'ownerdeptcode', this.$store.getters.dept.code)
            this.$set(this.model, 'ownerdeptname', this.$store.getters.dept.fullname)
            this.$set(this.model, 'deptcode', this.$store.getters.dept.code)
            this.$set(this.model, 'deptname', this.$store.getters.dept.fullname)
            // 组织信息
            this.$set(this.model, 'ownerorgcode', this.$store.getters.org.code)
            this.$set(this.model, 'ownerorgname', this.$store.getters.org.name)
            this.$set(this.model, 'orgcode', this.$store.getters.org.code)
            this.$set(this.model, 'orgname', this.$store.getters.org.name)
          }
        } else if (this.disableEditSubmit === false) {
          this.title = '编辑' + this.moduleTitle
          this.queryData(this.id).then(_ => {
            this.loaded()
          })
        } else {
          this.title = '查看' + this.moduleTitle
          this.queryData(this.id).then(_ => {
            this.loaded()
          })
        }
      })
    },
    // 删除预算明细
    handleDeleteForBudget(index) {
      this.modelForBudget.tableData.splice(index, 1)
    },
    /** 提交审批 */
    doSubmitApproval() {
      // 验证毛利率
      // 获取项目系统参数
      getAction('pm/project/getProjectSysParam', { projectOrg: this.model.ownerorgcode }).then(res => {
        this.projectSystemParam = res.result
        this.projectSystemParam.forEach(item => {
          switch (item.code) {
            case 'ProjectMinProfit':
              this.minProfit = item.paramvalue
              break
            case 'ProjectTipsMinProfit':
              this.tipsMinProfit = item.paramvalue
              break
            case 'ProjectTipsOfProfitTooLow':
              this.messageMinprofit = item.paramvalue
              break
            case 'ProjectMessageOftipsMinProfit':
              this.messageTipsMinProfit = item.paramvalue
              break
          }
        })
        if (
          parseFloat(this.minProfit) < this.computeGrossProfitRate &&
          this.computeGrossProfitRate < parseFloat(this.tipsMinProfit)
        ) {
          this.$tap
            .confirm(
              '该项目毛利率为:' + this.computeGrossProfitRate * 100 + this.messageTipsMinProfit,
              {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
              }
            )
            .then(() => {
              // 校验预算明细
              var resultForValidate = false
              this.$refs['budgetForm'].validate(valid => {
                if (valid) {
                  resultForValidate = true
                } else {
                  resultForValidate = false
                }
              })
              if (!resultForValidate) {
                this.tabName = 'bugetInfo'
                this.$message({
                  showClose: true,
                  message: '您填写的预算信息有误，请检查预算信息！',
                  type: 'error'
                })
                return false
              } else {
                // 添加预算明细进参数
                this.$set(this.model, 'budgetDetails', this.modelForBudget.tableData)
                // 计算预算金额
                var budgetmoneyTotal = 0
                this.modelForBudget.tableData.forEach(item => {
                  budgetmoneyTotal = item.budgetmoney + budgetmoneyTotal
                })
                this.$set(this.model, 'budgetmoney', budgetmoneyTotal)
              }
              if (!this.url.submit) {
                this.$tap.alert('请设置审批地址!', 'warning')
                return
              }
              this.submitLoading = true
              this.$tap
                .confirm('确定提交审批吗？提交后，单据内容不可修改！')
                .then(_ => {
                  if (!this.beforeApproval()) {
                    return
                  }
                  putAction(this.url.submit, this.model).then(res => {
                    if (res.success) {
                      this.$tap.message(res.message, 'success')
                      this.queryData(this.model.id)
                      this.afterApproval()
                    } else {
                      this.$tap.alert(res.message, 'warning')
                    }
                    this.submitLoading = false
                  })
                })
                .catch(_ => {
                  this.submitLoading = false
                })
              return true
            })
            .catch(() => {
              return
            })
        } else if (this.computeGrossProfitRate < parseFloat(this.minProfit)) {
          this.$message.error(
            '该项目毛利率为' + this.computeGrossProfitRate * 100 + this.messageMinprofit
          )
        } else {
          // 校验预算明细
          var resultForValidate = false
          this.$refs['budgetForm'].validate(valid => {
            if (valid) {
              resultForValidate = true
            } else {
              resultForValidate = false
            }
          })
          if (!resultForValidate) {
            this.tabName = 'bugetInfo'
            this.$message({
              showClose: true,
              message: '您填写的预算信息有误，请检查预算信息！',
              type: 'error'
            })
            return false
          } else {
            // 添加预算明细进参数
            this.$set(this.model, 'budgetDetails', this.modelForBudget.tableData)
            // 计算预算金额
            var budgetmoneyTotal = 0
            this.modelForBudget.tableData.forEach(item => {
              budgetmoneyTotal = item.budgetmoney + budgetmoneyTotal
            })
            this.$set(this.model, 'budgetmoney', budgetmoneyTotal)
          }
          if (!this.url.submit) {
            this.$tap.alert('请设置审批地址!', 'warning')
            return
          }
          this.submitLoading = true
          this.$tap
            .confirm('确定提交审批吗？提交后，单据内容不可修改！')
            .then(_ => {
              if (!this.beforeApproval()) {
                return
              }
              putAction(this.url.submit, this.model).then(res => {
                if (res.success) {
                  this.$tap.message(res.message, 'success')
                  this.queryData(this.model.id)
                  this.afterApproval()
                } else {
                  this.$tap.alert(res.message, 'warning')
                }
                this.submitLoading = false
              })
            })
            .catch(_ => {
              this.submitLoading = false
            })
          return true
        }
      })
    },
    /** 保存确认 */
    doSubmitEdit() {
      this.focuxItem = ''
      // 获取项目系统参数
      getAction('pm/project/getProjectSysParam', { projectOrg: this.model.ownerorgcode }).then(res => {
        this.projectSystemParam = res.result
        this.projectSystemParam.forEach(item => {
          switch (item.code) {
            case 'ProjectMinProfit':
              this.minProfit = item.paramvalue
              break
            case 'ProjectTipsMinProfit':
              this.tipsMinProfit = item.paramvalue
              break
            case 'ProjectTipsOfProfitTooLow':
              this.messageMinprofit = item.paramvalue
              break
            case 'ProjectMessageOftipsMinProfit':
              this.messageTipsMinProfit = item.paramvalue
              break
          }
        })
        // 验证毛利率
        if (
          parseFloat(this.minProfit) < this.computeGrossProfitRate &&
          this.computeGrossProfitRate < parseFloat(this.tipsMinProfit)
        ) {
          this.$tap
            .confirm(
              '该项目毛利率为:' + this.computeGrossProfitRate * 100 + this.messageTipsMinProfit,
              {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
              }
            )
            .then(() => {
              // 校验预算明细
              var resultForValidate = false
              this.$refs['budgetForm'].validate(valid => {
                if (valid) {
                  resultForValidate = true
                } else {
                  resultForValidate = false
                }
              })
              if (!resultForValidate) {
                this.tabName = 'bugetInfo'
                this.$message({
                  showClose: true,
                  message: '您填写的预算信息有误，请检查预算信息！',
                  type: 'error'
                })
                return false
              } else {
                // 添加预算明细进参数
                this.$set(this.model, 'budgetDetails', this.modelForBudget.tableData)
                // 计算预算金额
                var budgetmoneyTotal = 0
                this.modelForBudget.tableData.forEach(item => {
                  budgetmoneyTotal = item.budgetmoney + budgetmoneyTotal
                })
                this.$set(this.model, 'budgetmoney', budgetmoneyTotal)
              }
              // debugger
              if (!this.beforeSubmit()) {
                return
              }
              this.$refs.form.validate(valid => {
                if (valid) {
                  if (this.isAdd) {
                    this.doAdd()
                  } else {
                    this.doEdit()
                  }
                } else {
                  this.tabName = 'projectInfo'
                  this.$message({
                    showClose: true,
                    message: '您填写的立项信息有误，请检查立项信息！',
                    type: 'error'
                  })
                  return false
                }
              })
            })
            .catch(() => {
              return
            })
        } else if (this.computeGrossProfitRate < parseFloat(this.minProfit)) {
          this.$message.error(
            '该项目毛利率为' + this.computeGrossProfitRate * 100 + this.messageMinprofit
          )
        } else {
          // 校验预算明细
          var resultForValidate = false
          this.$refs['budgetForm'].validate(valid => {
            if (valid) {
              resultForValidate = true
            } else {
              resultForValidate = false
            }
          })
          if (!resultForValidate) {
            this.tabName = 'bugetInfo'
            this.$message({
              showClose: true,
              message: '您填写的预算信息有误，请检查预算信息！',
              type: 'error'
            })
            return false
          } else {
            // 添加预算明细进参数
            this.$set(this.model, 'budgetDetails', this.modelForBudget.tableData)
            // 计算预算金额
            var budgetmoneyTotal = 0
            this.modelForBudget.tableData.forEach(item => {
              budgetmoneyTotal = item.budgetmoney + budgetmoneyTotal
            })
            this.$set(this.model, 'budgetmoney', budgetmoneyTotal)
          }
          // debugger
          if (!this.beforeSubmit()) {
            return
          }
          this.$refs.form.validate(valid => {
            if (valid) {
              if (this.isAdd) {
                this.doAdd()
              } else {
                this.doEdit()
              }
            } else {
              this.tabName = 'projectInfo'
              this.$message({
                showClose: true,
                message: '您填写的立项信息有误，请检查立项信息！',
                type: 'error'
              })
              return false
            }
          })
        }
      })
    },
    /** 执行编辑提交 */
    doEdit() {
      this.saveLoading = true
      // 校验预算明细
      var resultForValidate = false
      this.$refs['budgetForm'].validate(valid => {
        if (valid) {
          resultForValidate = true
        } else {
          resultForValidate = false
        }
      })
      if (!resultForValidate) {
        this.tabName = 'bugetInfo'
        this.$message({
          showClose: true,
          message: '您填写的预算信息有误，请检查预算信息！',
          type: 'error'
        })
        return false
      } else {
        // 添加预算明细进参数
        this.$set(this.model, 'budgetDetails', this.modelForBudget.tableData)
        // 计算预算金额
        var budgetmoneyTotal = 0
        this.modelForBudget.tableData.forEach(item => {
          budgetmoneyTotal = item.budgetmoney + budgetmoneyTotal
        })
        this.$set(this.model, 'budgetmoney', budgetmoneyTotal)
      }
      putAction(this.url.edit, this.model)
        .then(res => {
          if (res.success) {
            this.$tap.message(res.message, 'success')
            this.visible = false
            this.$emit('refresh')
          } else {
            this.$tap.alert(res.message, 'warning')
          }
          this.afterSubmit()
          this.saveLoading = false
        })
        .catch(err => {
          this.saveLoading = false
        })
    },

    assignDefaultValue() {
      if (this.isAdd) {
        // if (this.codeModel.flowidList && this.codeModel.flowidList.length > 0) {
        //   this.$set(this.model, 'flowid', parseInt(this.codeModel.flowidList[0].id))
        //   this.$set(this.model, 'dispflowid', parseInt(this.codeModel.flowidList[0].name))
        // }
        // this.$set(this.model, 'orgcode', this.org.code)
        // this.$set(this.model, 'orgname', this.org.name)
        // this.$set(this.model, 'deptcode', this.dept.code)
        // this.$set(this.model, 'deptname', this.dept.fullname)
        this.$set(this.model, 'orgcodevisible', this.org.code)
        this.$set(this.model, 'usercode', this.user.code)
        this.$set(this.model, 'username', this.user.name)
        this.$set(this.model, 'docdate', new Date())
      }
    },
    afterDelApproval() {
      this.disableAttachmentButton = false
    },
    /** 执行新增提交 */
    doAdd() {
      this.saveLoading = true
      // 增加唯一单号
      this.$set(this.model, 'billuid', this.uid)
      postAction(this.url.add, this.model)
        .then(res => {
          if (res.success) {
            this.$tap.message('添加成功', 'success')
            this.queryData(res.result.id)
            this.disableAttachmentButton = false
            this.isAdd = false
          } else {
            this.$tap.alert(res.message, 'warning')
          }
          this.afterSubmit()
          this.saveLoading = false
        })
        .catch(err => {
          this.saveLoading = false
        })
    },
    loaded() {
      if (this.isAdd === false && this.disableEditSubmit === true) {
        var params = {
          sourceType: 'PmProject',
          sourceId: this.model.id
        }
        this.disableAttachmentButton = false
        getAction('/cbo/attachment/calculateCount', params).then((res) => {
          if (res.success) {
            if (res.result === 0) {
              this.disableAttachmentButton = true
              this.$emit('refresh')
            }
          }
        })
      }
      const { code } = this.model
      var e = {
        qry_code: code
      }
      getAction('pm/project/list', e).then(res => {
        if (res.success) {
          this.budgetmoneydb = res.result.dataList[0].budgetmoney
        }
      })
      // 页面加载完毕执行
      if (!this.isAdd) {
        this.title = this.title + `（单据编号：${this.model.docno}）`
        // 查询项目预算
        getAction('pm/budgetLine/list', { projectid: this.id, state: 9 }).then(res => {
          this.modelForBudget.tableData = res.result.dataList
          console.log(res)
        })
      }
      // 添加页面，自动给项目进展状态赋值（0：待立项）
      if (this.isAdd) {
        this.modelForBudget.tableData = [
          {
            costtype: '',
            budgetmoney: undefined,
            note: ''
          }
        ]
        this.$set(this.model, 'projectstate', 0)
      }
      this.assignDefaultValue()
    },
    /** 打开客户名称参照 */
    openpmCustomerRefDialog() {
      this.$refs.pmCustomerRef.visible = true
    },
    // // 所属公司点击确认
    // ownerorgnameConfirm(selectionRow) {
    //     this.$set(this.model, 'ownerorgcode', selectionRow[0].code)
    //     this.$set(this.model, 'ownerorgname', selectionRow[0].name)
    // },
    // 所属部门点击确认
    // ownerdeptnameConfirm(selectionRow) {
    //     this.$set(this.model, 'ownerdeptcode', selectionRow[0].code)
    //     this.$set(this.model, 'ownerdeptname', selectionRow[0].name)
    // },
    onSelectDept(selectedDepts) {
      const selectedDept = selectedDepts[0]
      const { id, code, fullname } = selectedDept
      this.$set(this.model, 'ownerdeptcode', code)
      this.$set(this.model, 'ownerdeptname', fullname)
      this.$set(this.model, 'deptcode', code)
      this.$set(this.model, 'deptname', fullname)
      const param = {
        deptId: id
      }
      getAction(this.url.queryOrgByDeptId, param).then(res => {
        if (res.success) {
          const { code: orgcode, name: orgname } = res.result
          this.$set(this.model, 'ownerorgcode', orgcode)
          this.$set(this.model, 'ownerorgname', orgname)
          this.$set(this.model, 'orgcode', orgcode)
          this.$set(this.model, 'orgname', orgname)
        } else {
          this.$tap.alert('已选部门关联公司信息错误，请联系系统管理员')
        }
      })
    },
    // 销售经理点击取确认
    areamanagernameConfirm(selectionRow) {
      this.$set(this.model, 'areamanagercode', selectionRow[0].code)
      this.$set(this.model, 'areamanagername', selectionRow[0].name)
    },
    // 项目经理点击确认
    projectmanagernameConfirm(selectionRow) {
      this.$set(this.model, 'projectmanagercode', selectionRow[0].code)
      this.$set(this.model, 'projectmanagername', selectionRow[0].name)
    },
    /** 获取客户名称参数数据 */
    getpmCustomerRefData(selectionRow, selectKey, selectionValue) {
      this.$set(this.model, 'dispcustomercode', selectionRow.name)
      this.$set(this.model, 'customercode', selectionRow.id)
    },
    // 获取省份信息
    selectProvince(data) {
      this.$set(this.model, 'province', data.value)
      this.$set(this.model, 'provincecode', data.code)
    }
  }
}
</script>
<style scoped>
/* .aaa {
    margin-bottom: 0px;
}
.aaa >>> .el-form-item {
    margin-bottom: 0px;
} */
/* .aaa >>> .el-form-item__error {
    float: right;
    margin-top: -20px;
    margin-left: 30px;
} */
.aaa >>> .el-select .el-input.is-disabled .el-input__inner {
  cursor: not-allowed;
  color: #606266;
}
.aaa >>> .el-input.is-disabled .el-input__inner {
  background-color: #f5f7fa;
  border-color: #e4e7ed;
  color: #606266;
  cursor: not-allowed;
}
</style>
